APM.ConfigUsermanageController = Ember.Controller.extend({
	form: {
		cossPort:"",
		cossIp:"",
		account:"",
		name:"",
		password:"",
		repassword:"",
		status:0,
		id:"",
		confType:"8"
	},  
    roles: Ember.computed(function(key, value){
   		if(arguments.length == 1){
   			this.requireRoles();
   			return Ember.A();
   		}else{
   			return value;
   		}        
   	}),
    /*
		列配置
	*/
   	columns : [
		{
			headerText: "用户名",
			dataKey:"name",
			width: 200,
			allowSort: false,
			ensurePxWidth: true
		},
		{
			headerText: "账号",
			dataKey:"account",
			width: 200,
			allowSort: false,
			ensurePxWidth: true
		},
		{
			headerText: "角色",
			dataKey:"roleName",
			allowSort: false,
			ensurePxWidth: true,
			cellFormatter: function (args, colume) {
				if (args.row.type & $.wijmo.wijgrid.rowType.data) {
					var ctrl = this.get("controller"),
						user = args.row.data;
					if(user.role == 0) {
						args.$container.text("系统管理人员");
					} else if(user.role == 1){
						args.$container.text("应用管理人员");
					} else if(user.role == 2){
						args.$container.text("普通人员");
					}
					return true;
				}
			}
		},
		{
			headerText: "操作",
			dataKey:"state",
			width: 250,
			allowSort: false,
			ensurePxWidth: true,
			cellFormatter: function (args, colume) {
				if (args.row.type & $.wijmo.wijgrid.rowType.data) {
					var ctrl = this.get("controller"),
						user = args.row.data;
					if(!user.isCurrent) {
						if(user.status) {
							var enable = $('<button class="u-btn-blue margin-style" title="启用">启用</button>');                            
							enable.appendTo(args.$container).on("click",function(){
								ctrl.enable(user.id,user.status);
							});
						} else {
							var disable = $('<button class="u-btn-blue margin-style" title="禁用">禁用</button>');
							disable.appendTo(args.$container).on("click",function(){
								ctrl.enable(user.id,user.status);
							});
						}
					}	

					var upd = $('<button class="u-btn-blue margin-style" title="修改" {{action "updOpenDialog" user}}>编辑</button>');
					upd.appendTo(args.$container).on("click",function(){
						ctrl.updOpenDialog(user);
					});
					var edit = $('<button class="u-btn-blue margin-style" title="修改密码">修改密码</button>');
					edit.appendTo(args.$container).on("click",function(){
						ctrl.pwdOpenDialog(user);
					});
                    if(!user.isCurrent) {
                        var dele = $('<button class="u-btn-danger  margin-style" title="删除">删除</button>');
                        dele.appendTo(args.$container).on("click",function(){
                            ctrl.deleteUser(user.id);
                        });
                    }
					return true;
				}
			}
		}
	],

   	requireRoles: function(){
   		var ctrl = this;
   		ctrl.store.ajax("GET", "configs/systemConfig",{
   			configItem:"user.role"
   		}).then(function(response){
   			var user_role=response.configData.user_role.replace(/'/g,"\"");
   			if(user_role){
	   			var roles=JSON.parse(user_role);
	   			ctrl.set("roles", Ember.A(roles));
   			}else{
   				alert("对不起,角色列表解析失败！");
   			}
   		});
   	},

    initConfData: function(){
   		var ctrl = this;
        ctrl.set("currentUserId", this.get('auth.user.id'));
        ctrl.set("currentUser",  this.get('auth.user'));

        pageIndex = this.get("pageIndex")||0;

   		ctrl.store.ajax("GET", "configs/usermanage",{
			pageIndex : pageIndex,
			pageSize : 10
		}).then(function(response){
   	 		var users=response.result;
   	 		if(ctrl.get('currentUserId')){
	   	 		if(users){
	   	 			var userModels = Ember.A();

	   	 			Ember.A(users).forEach(function(item) {
	   	 				item.isCurrent = ctrl.currentUserId == item.id;
	   	 				userModels.push(item);
	   	 			});

	   				ctrl.set("users", userModels);
	   	 		}
	   	 	}else{
	   	 		ctrl.set("users", Ember.A(users));
	   	 	}

	   	 	ctrl.set("pageIndex",response.meta["pageIndex"]);
			ctrl.set("pageSize",response.meta["pageSize"]);
			ctrl.set("totalRows",response.meta["total"]);
   		});   			
   	},
       
	//用户查询列表存放数组
	users : Ember.A(),
	   	
	checkFormValid: function(){
   		var form = this.get("form");
   		this.set("formTip", null);
   		if( form.account == "" || form.account == null){
   			this.set("formTip", "请输入账号！");
   			return false;
   		}else if( form.name == "" || form.name == null){
   			this.set("formTip", "请输入用户名！");
   			return false;
   		}else if( form.password == "" || form.password == null){
   			this.set("formTip", "请输入密码");
   			return false;
   		}else if( form.repassword == "" || form.repassword == null){
   			this.set("formTip", "请输入重复密码！");
   			return false;
   		}else if( form.password != form.repassword){
   			this.set("formTip", "两次输入密码不一致！");
   			return false;
   		}
   		this.set("formTip", null);
   		return true;
   	},

   	enable: function(userId,status){
		var ctrl = this;
		var statusTemp;
		var userSelf=ctrl.get('currentUser');
		if(userSelf){
			var uid=userSelf.id.trim();
			if(uid == userId){
				alert("对不起,您不能启用或者禁用自身账户!");
			}else{
				if(status){
					// if(!confirm("确定启用该用户吗？")){
					// 	return false;
					// }
					// statusTemp=0;
					confirmDialog("确定启用该用户吗？").then(function(){
						statusTemp=0;
						ctrl.store.ajax("PUT", "configs/usermanage/status", {
							id:userId,
							status:statusTemp
						}).then(function(response){
							//todo: 保存结果返回逻辑
							if(response.status=="success"){
								if(statusTemp==1){
									alertTip("禁用成功！");
								}
								if(statusTemp==0){
									alertTip("启用成功！");
								}
							}else{
								alertTip(response.message);
							}
							ctrl.send("queryUser");
						});
					});
					
				}else{
					// if(!confirm("确定禁用该用户吗？")){
					// 	return false;
					// }
					// statusTemp=1;
					confirmDialog("确定禁用该用户吗？").then(function(){
						statusTemp=1;
						ctrl.store.ajax("PUT", "configs/usermanage/status", {
							id:userId,
							status:statusTemp
						}).then(function(response){
							//todo: 保存结果返回逻辑
							if(response.status=="success"){
								if(statusTemp==1){
									alertTip("禁用成功！");
								}
								if(statusTemp==0){
									alertTip("启用成功！");
								}
							}else{
								alertTip(response.message);
							}
							ctrl.send("queryUser");
						});
					});
					
				}

				
			}
		}else{
				alert("当前登录账户信息为空,请您先登录!");
		};
	},

	deleteUser: function(userId){
		var ctrl = this;
		var form = ctrl.get("form");
		var userSelf = ctrl.get('currentUser');
		ctrl.set("formTip", null);
		if(userSelf){
			var uid=userSelf.id.trim();
			if(uid == userId){
				alert("对不起,您不能删除自身账户!");
			}else{
				confirmDialog("确定要删除此用户吗？")
				.then(function(){
					ctrl.store.ajax("DELETE", "configs/usermanage/"+userId, {
						
					}).then(function(response){
						if(response.status=="success"){
							//todo: 保存成功逻辑
							alertTip("删除用户成功！");
						}else{
							ctrl.set("formTip", response.message);
						}
						ctrl.send("queryUser");
					});
				});
			}
		}else{
			alert("当前登录账户信息为空,请您先登录!");
		};
	},

	//修改对话框打开方法
	updOpenDialog: function(obj){
	    this.set("formTip", null);
        var dialog = Broada.getView("usermanage_upd");
        this.set("updUserTip",null);
        Broada.getView("usermanage_upd").openDialog();
        if(obj){            
			this.set("form.account",obj.account);
			this.set("form.name",obj.name);
			this.set("form.id",obj.id);
			this.set("form.password",obj.password);
			this.set("form.role",obj.role);
			this.set("form.status",obj.status);
		}
    },
  
    //修改密码对话框打开方法
	pwdOpenDialog: function(obj){
		this.set("formTip", null);
		this.set("updPWD", null);
		this.set("form.repassword",null);
		this.set("form.password",null);
		this.set("form.account",null);
		var dialog = Broada.getView("usermanage_updpwd");
		Broada.getView("usermanage_updpwd").openDialog();
    	if(obj){
			this.set("form.account",obj.account);
			this.set("form.id",obj.id);
		}
	},
	
	actions: {
		reset : function() {
			this.set("formTip", null);
			this.set("saveResult", null);
		},
		
		//添加对话框打开方法
		openDialog: function(){
		   this.set("formTip", null);
		   this.set("form.account",null);
		   this.set("form.name",null);
		   this.set("form.id",null);
		   this.set("form.password",null);
		   this.set("form.repassword",null);
		   this.set("form.role", 1);           
           var dialog = Broada.getView("usermanage_add");
           Broada.getView("usermanage_add").openDialog();
        },
       
        closeDialog: function(diaIndex){
    	    if(diaIndex=="1"){
    		    Broada.getView("usermanage_add").closeDialog();
    		}
    	    if(diaIndex=="2"){
    		    Broada.getView("usermanage_upd").closeDialog();
    		}
    	    if(diaIndex=="3"){
    		    Broada.getView("usermanage_updpwd").closeDialog();
    		}
        },
       
        queryUser :function(){
    	    var ctrl=this;
    	    pageIndex = this.get("pageIndex")||0;
    	    ctrl.store.ajax("GET", "configs/usermanage", {
				pageIndex : pageIndex,
				pageSize : 10
			}).then(function(response){
      	 		var users=response.result;
	      	 	if(ctrl.get('currentUser')){
		   	 		if(users){
		   	 			var userModels = Ember.A();

		   	 			Ember.A(users).forEach(function(item) {
		   	 				item.isCurrent = ctrl.currentUserId == item.id;
		   	 				userModels.push(item);
		   	 			});

		   				ctrl.set("users", userModels);
		   	 		}
		   	 	}else{
		   	 		ctrl.set("users", Ember.A(users));
		   	 	}

		   	 	ctrl.set("pageIndex",response.meta["pageIndex"]);
				ctrl.set("pageSize",response.meta["pageSize"]);
				ctrl.set("totalRows",response.meta["total"]);
      		});
        },
       
		addUser: function(){
			if( !this.checkFormValid() ){
				return;
			}
			var ctrl = this;
			var form = this.get("form");

			ctrl.set("formTip", null);

			this.store.ajax("POST", "configs/usermanage", {
				account:form.account,
				name:form.name,
				password:form.password,
				role:form.role,
				status:0
			}).then(function(response){
				if(response.status=="success"){
					//todo: 保存成功逻辑
					alertTip("添加用户成功！");
					ctrl.send("closeDialog","1");
					ctrl.send("queryUser");
				}else if(response.status == "invalid"){
					ctrl.set("formTip", response.message);
				}
			});
		},
		
		updUser: function(){
			var ctrl = this;
			var form = this.get("form");
            var updUser = "";
            if(form.name == ""){
                updUser = "用户名";
                ctrl.set("updUserTip",updUser+"不能为空");
                return;
            }
			ctrl.set("formTip", null);
			this.store.ajax("PUT", "configs/usermanage", {
				account:form.account,
				name:form.name,
				password:form.password,
				role:form.role,
				id:form.id,
				status:form.status
			}).then(function(response){
				if(response.status=="success"){
					//todo: 保存成功逻辑
					alertTip("修改用户成功！");
				}else{
					alertTip(response.message);
				}
				ctrl.send("queryUser");
			});
			ctrl.send("closeDialog","2");
		},
		
		
	
		updatepwd: function(){
			var ctrl = this;
			var form = this.get("form");
			ctrl.set("formTip", null);
			if(form.password != form.repassword){
				ctrl.set("updPWD", "两次输入密码不一致,请重新输入!");
				ctrl.set("form.repassword",null);
				return false;
			}
			ctrl.store.ajax("PUT", "configs/usermanage/pwd", {
				userId:form.id,
				oldPass:null,
				newPass:form.password
			}).then(function(response){
				if(response.status=="success"){
					//todo: 保存成功逻辑
					alertTip("密码修改成功！");
				}else{
					//todo: 保存成功逻辑
					alertTip(response.message);
				}
			});
			ctrl.send("closeDialog","3");
		},

		pageIndexChanged: function(e, data, view){
			var pageNo = data.newPageIndex;
			this.set("pageIndex", pageNo);
			this.send("queryUser");
		}
	}		
});